import java.io.File;
import java.net.URL;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {

    public static Class<UserDefineFoo> clazz;

    public static CustomClassLoader cl;

    private static final ThreadLocal<Object> tl = new ThreadLocal<Object>();

    public static void main(String...args) throws Exception {
        loadFoo();
        /**
         * 不会打印 CustomClassLoader finalized!
        while (true) {
            System.gc();
            Thread.sleep(1000);
        }
         */

        int x = 1000;
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 1000, 1000, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(10));
        for(int i = 0; i < x; i++){
            poolExecutor.execute(new Runnable() {
                public void run() {
                    try {
                        clazz = (Class<UserDefineFoo>) cl.loadClass("UserDefineFoo");
                        Object foo = clazz.newInstance();
                        tl.set(foo);
                        clazz = null;
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        System.out.println("main end");
    }

    private static void loadFoo() throws Exception {
         cl = new CustomClassLoader(
                new URL("file:/Users/chenxin/Documents/code/small-experiment/jdk-learn/spi-run/target/classes/"));



//        cl = null;
    }


//    public static class Foo {
//
//        public Foo() {
//            byte[] bar = new byte[1000000];
//            System.out.println(this + " ClassLoader: " + this.getClass().getClassLoader());
//
//        }
//    }
}